package controllers

import (
	"bitbucket.org/alanwhen/infant-experience-class/enums"
	"bitbucket.org/alanwhen/infant-experience-class/models"
	"encoding/json"
	"github.com/astaxie/beego/orm"
)

type CourseApplyController struct {
	BaseController
}

func (u *CourseApplyController) Prepare() {
	u.BaseController.Prepare()
	u.checkAuthor("DataGrid")
}

func (u *CourseApplyController) Index() {
	u.checkLogin()
	u.Data["pageTitle"] = "课程申请列表"
	u.ActiveSidebarUrl()
	u.Data["canEdit"] = u.checkActionAuthor(u.controllerName, "Edit")
	u.Data["canApply"] = u.checkActionAuthor(u.controllerName, "Apply")
	u.setTpl("course_apply/index")
}

func (u *CourseApplyController) DataGrid() {
	var params models.CourseApplyQueryParam
	json.Unmarshal(u.Ctx.Input.RequestBody, &params)
	data, total := models.CourseApplyPageList(&params)
	u.BootstrapJson(total, data)
}

func (u *CourseApplyController) Edit() {
	if u.Ctx.Request.Method == "POST" {
		u.Save()
	}
	Id, _ := u.GetInt(":id", 0)
	m := &models.CourseApply{}
	var err error
	if Id > 0 {
		m, err = models.CourseApplyOne(Id)
		if err != nil {
			u.pageError("数据无效，请刷新后重试")
		}
	} else {

	}
	u.Data["m"] = m
	u.setTpl("course_apply/edit", "shared/layout_pullbox", "footer")
}

func (u *CourseApplyController) Save() {
	m := models.CourseApply{}
	o := orm.NewOrm()
	var err error
	if err = u.ParseForm(&m); err != nil {
		u.jsonResult(enums.JRCodeFailed, "获取数据失败", m.Id)
	}
	if m.Id > 0 {
		oM, err := models.CourseApplyOne(m.Id)
		if err != nil {
			u.jsonResult(enums.JRCodeFailed, "数据无效，请刷新后再试", m.Id)
		} else {
			m.CreateAt = oM.CreateAt
			if _, err := o.Update(&m); err != nil {
				u.jsonResult(enums.JRCodeFailed, "编辑失败", m.Id)
			}
		}
		u.jsonResult(enums.JRCodeSuccess, "编辑成功", m.Id)
	}
	u.jsonResult(enums.JRCodeFailed, "数据无效", m.Id)
}
